use std::{fmt::Display, ops::Deref};

use reqwest::Client;
use serde::{Deserialize, Serialize};

use crate::common::Response;

#[derive(Clone, Debug, Serialize)]
pub struct CheckEncryptedDataReq {
    encrypted_msg_hash: String,
}

impl CheckEncryptedDataReq {
    pub fn new<T>(msg: T) -> Self
    where
        T: AsRef<str>,
    {
        Self {
            encrypted_msg_hash: msg.as_ref().to_owned(),
        }
    }
}

type Res = Response<CheckEncryptedDataRes>;

#[derive(Clone, Debug, Deserialize)]
pub struct CheckEncryptedDataRes {
    pub valid: bool,
    pub create_time: u32,
}

pub async fn check_encrypted_data<T>(
    token: T,
    hash: &CheckEncryptedDataReq,
) -> Result<Res, reqwest::Error>
where
    T: Deref + Display,
{
    let client = Client::new();
    let url = format!(
        "https://api.weixin.qq.com/wxa/business/checkencryptedmsg?access_token={}",
        token
    );
    client
        .post(url)
        .json(hash)
        .send()
        .await?
        .json::<Res>()
        .await
}
